package dao

import (
	_ "github.com/go-sql-driver/mysql"
	"html/template"
	"log"
	"net/http"
	"os"
	"regexp"
	"strings"
)

func Init() {

	//启动时日志记录
	LogServiceStart()

	//Redis
	InitRedis()

	//Mysql
	InitMysql()

	//写入数据缓存
	InitPageConfig()

	//Log
	InitLog()

}

//写入数据缓存
func InitPageConfig() {
	Cache = make(map[string]interface{})
	//数据在启动的时候就写入缓存
	OptData := GetFieldsAll()
	for _, v := range OptData {
		Cache[v.Key] = v
	}
}

/**
公用处理逻辑
*/
func CommonAction(r *http.Request, w http.ResponseWriter) {
	go func() {
		LogRequest(r)
	}()

}

//InitLog
func InitLog() {
	fd, _ := os.OpenFile(RunCFG.ErrorLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	log.SetOutput(fd)
}

/**
SendResult
*/
func SendResult(w http.ResponseWriter, status int, message string, data interface{}) (err error) {
	var d = Return{Error: status, Message: message, Data: data}
	err = d.ResponseJson(w)
	return
}

/**
显示跳转页面
*/
func RedirectPage(w http.ResponseWriter, title, message, toUrl string, httpCode, waitSecond int) {
	t, err := template.New("redirect.html").Funcs(FuncMap).ParseFiles("templates/redirect.html", "templates/pub_inc.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	param := struct {
		Title      template.HTML
		Message    template.HTML
		ToUrl      template.HTML
		HttpCode   int
		WaitSecond int
	}{
		Title:      template.HTML(title),
		Message:    template.HTML(message),
		ToUrl:      template.HTML(toUrl),
		HttpCode:   httpCode,
		WaitSecond: waitSecond,
	}

	//直接301临时跳转
	if waitSecond == 0 {
		w.Header().Set("Location", toUrl)
		w.WriteHeader(301)
		return
	}

	w.WriteHeader(httpCode) //必须要在Execute之前执行
	t.Execute(w, param)
}

func TrimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}
